//
//  NetworkTools.swift
//  WeiBoSwift
//
//  Created by 吴斌 on 2022/9/23.
//

import AFNetworking

/*
 测试网络接口网:http://httpbin.org
 */

// 定义枚举类型 swfit枚举值可以为字符串类型
enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {

    // 定义一个单例 let是线程安全的 
    static let shareInstance : NetworkTools = {
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
}

// MARK: - 封装请求方法
extension NetworkTools {
    func request(methodType: RequestType, urlString: String, parameters: [String : Any], finished: @escaping (_ result: Any?, _ error: Error?) -> ()) {
        
        // 1.定义成功的回调闭包
        let successCallBack = { (task: URLSessionDataTask, result: Any?) -> Void in
            finished(result, nil)
        }
        
        // 2.定义失败的回调闭包
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> Void in
            finished(nil, error)
        }
        
        // 3.发送网络请求
        if methodType == .GET {
            get(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
            post(urlString, parameters: parameters, headers: nil, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}

// MARK: - 请求AccessToken
extension NetworkTools {
    func loadAccessToken(code: String, finished: @escaping(_ result: [String : Any]?, _ error: Error?)   -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求的参数
        let paramters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        
        // 3.发送网络请求
        request(methodType: .POST, urlString: urlString, parameters: paramters) { result, error in
            finished(result as? [String : Any], error)
        }
    }
}

// MARK: - 请求用户的信息
extension NetworkTools {
    func loadUserInfo(access_token: String, uid: String, finished: @escaping(_ result: [String : Any]?, _ error: Error?) -> Void){
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 2.获取请求的参数
        let paramters = ["access_token" : access_token, "uid" : uid]
        
        // 3.发送网络请求
        request(methodType: .GET, urlString: urlString, parameters: paramters) { result, error in
            finished(result as? [String : Any], error)
        }
    }
}

// MARK: - 请求首页数据
extension NetworkTools {
    func loadStatuses(finished : @escaping(_ result : [[String : Any]]?,_ error : Error?) -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 2.获取请求的参数
        guard let access_token = UserAccountViewModel.shareIntance.account?.access_token else {
            return;
        }
        let parameters = ["access_token" : access_token]
        
        // 3.发送网络请求
        request(methodType: .GET, urlString: urlString, parameters: parameters) { result, error in
            // 1.获取字典的数据
            guard let resultDict = result as? [String : Any] else {
                finished(nil, error)
                return
            }
            
            // 2.将数组数据回调给外界控制器
            finished(resultDict["statuses"] as? [[String : Any]], error)
            
        }
    }
}
